package com.ldy.biz.shop.web;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ldy.biz.shop.entity.Category;
import com.ldy.biz.shop.entity.Order;
import com.ldy.biz.shop.entity.OrderItem;
import com.ldy.biz.shop.entity.Product;
import com.ldy.biz.shop.entity.ShopInfo;
import com.ldy.biz.shop.service.CategoryService;
import com.ldy.biz.shop.service.OrderItemService;
import com.ldy.biz.shop.service.OrderService;
import com.ldy.biz.shop.service.ProductService;
import com.ldy.biz.shop.service.ShopInfoService;
import com.ldy.core.common.Result;
import com.ldy.core.entity.BaseFile;
import com.ldy.core.service.BaseFileService;

/**
 * 小程序接口
 */
@RestController
@RequestMapping("/open-api")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class OpenApiController {
	
	private static final Logger logger = LoggerFactory.getLogger(OpenApiController.class);

	@Autowired
	private ProductService productService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private BaseFileService fileService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderItemService orderItemService;
	
	@Autowired
	private ShopInfoService shopInfoService;
	
	/**
	 * 商品列表查询
	 * 
	 * @return
	 */
	@PostMapping("/product/selectList")
	public Result productList(String shopCode) {
		Assert.hasText(shopCode, "参数不能为空");
		QueryWrapper<Product> query = new QueryWrapper<>();
		query.eq("org_code", shopCode);
		query.eq("status", 1);
		query.orderByAsc("order_no");
		return Result.success(productService.list(query));
	}
	
	/**
	 * 商品分类查询
	 * 
	 * @return
	 */
	@PostMapping("/category/selectList")
	public Result selectList(String shopCode) {
		Assert.hasText(shopCode, "参数不能为空");
		QueryWrapper<Category> query = new QueryWrapper<>();
		query.eq("org_code", shopCode);
		query.orderByAsc("order_no");
		return Result.success(categoryService.list(query));
	}
	

	/**
	 * 商品图片
	 * @param refId
	 * @param response
	 * @return
	 */
	@GetMapping("/product/img")
	public ResponseEntity<Object> productImg(String refId, HttpServletResponse response) {
		logger.debug("request:{}, params:[refId:{}]", "下载", refId);
		try {
			QueryWrapper<BaseFile> query = new QueryWrapper<>();
			query.eq("ref_id", refId);
			query.eq("type", "productImg");
			query.select("id");
			query.orderByDesc("create_time");
			List<BaseFile> list = fileService.list(query);
			if (CollectionUtils.isEmpty(list)) {
				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.failure("Not Fund"));
			}
			BaseFile file = fileService.getById(list.get(0).getId());
			Assert.notNull(file, "不存在下载文件");
			// 下载
			ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(file.getContent()));
			Resource resource = new InputStreamResource(bis);
			String  encodedFileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString());
			return ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
					.contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
		} catch (Exception e) {
			logger.error("下载异常: {}", e);
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.failure(e.getMessage()));
		}
	}
	
	
	/**
	 * 下单
	 * 
	 * @return
	 */
	@PostMapping("/order/create")
	public Result createOrder(@RequestBody Order order) {
		Assert.notNull(order, "参数不能为空");
		return Result.success(productService.createOrder(order));
	}
	
	/**
	 * 支付成功
	 * 
	 * @return
	 */
	@PostMapping("/order/pay")
	public Result orderPay(String orderId) {
		Assert.hasText(orderId, "参数不能为空");
		productService.orderPay(orderId);
		return Result.success();
	}
	
	/**
	 * 取消订单
	 * 
	 * @return
	 */
	@PostMapping("/order/cancel")
	public Result orderCancel(String orderId) {
		Assert.hasText(orderId, "参数不能为空");
		productService.orderCancel(orderId);
		return Result.success();
	}
	
	/**
	 * 订单分页列表
	 * 
	 * @return
	 */
	@PostMapping("/order/selectPage")
	public Result selectPageOrder(int current, int size, String shopCode, String customerId) {  
		Assert.hasText(customerId, "参数不能为空");
		Assert.hasText(shopCode, "参数不能为空");
		Page<Order> page = new Page<Order>(current, size);
		QueryWrapper<Order> query = new QueryWrapper<>();
		// 查询和我有关系
		query.eq("org_code", shopCode);
		query.eq("customer_id", customerId);
		query.orderByDesc("order_time");
		return Result.success(orderService.page(page, query));
	}
	
	/**
	 * 订单详情列表
	 * 
	 * @return
	 */
	@PostMapping("/order/item/selectList")
	public Result selectListOrderItem(String orderId) {  
		Assert.hasText(orderId, "参数不能为空");
		QueryWrapper<OrderItem> query = new QueryWrapper<>();
		// 查询和我有关系
		query.eq("order_id", orderId);
		return Result.success(orderItemService.list(query));
	}
	
	/**
	 * 动态分页列表
	 * 
	 * @return
	 */
	@PostMapping("/info/selectPage")
	public Result selectPageInfo(int current, int size, String shopCode) { 
		Assert.hasText(shopCode, "参数不能为空");
		Page<ShopInfo> page = new Page<ShopInfo>(current, size);
		QueryWrapper<ShopInfo> query = new QueryWrapper<>();
		// 查询和我有关系
		query.eq("org_code", shopCode);
		query.eq("status", 1);
		query.orderByDesc("issue_time, title");
		return Result.success(shopInfoService.page(page, query));
	}
}
